package com.sixbing.demo.subscriber;

import com.company.module.net.bean.BaseBean;
import com.google.gson.JsonSyntaxException;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.net.SocketTimeoutException;

import io.reactivex.observers.DisposableObserver;
import retrofit2.HttpException;


/**
 * desc :订阅拦截请求返回数据，统一处理
 * user : sixbing
 * time : 2019-03-29 15:33.
 * version : 1.0
 */
public abstract class MySubscriber<T> extends DisposableObserver<BaseBean<T>> {
    public MySubscriber() {
    }

    abstract public void onSuccess(BaseBean<T> tResponse);

    abstract public void onFailed(BaseBean<T> tResponse);

    public void afterError(Throwable e) {

    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        String message = "";
        String code = "500";
        int status = -1;
        if (e instanceof SocketTimeoutException) {
            message = "连接超时";
        } else if (e instanceof JsonSyntaxException) {
            message = "解析异常：" + e.getMessage();
        } else if (e instanceof HttpException) {
            message = "请求异常：" + e.getMessage();
        } else {
            message = "数据获取失败！onError" + e.getMessage();
        }
        BaseBean baseBean = new BaseBean();
        baseBean.setCode(code);
        baseBean.setState(status);
        baseBean.setMsg(message);
        onFailed(baseBean);
        afterError(e);
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onNext(BaseBean<T> tResponse) {
        if (tResponse == null) {
            BaseBean baseBean = new BaseBean();
            baseBean.setCode("404");
            baseBean.setState(0);
            baseBean.setMsg("数据解析异常！");
            onFailed(baseBean);
        } else if (tResponse.getState() == 1) {
            onSuccess(tResponse);
        } else if (tResponse.getState() == 2) {
            onFailed(tResponse);
        } else {
            onFailed(tResponse);
        }
    }
}